package com.geeklan.base.utils;

import android.app.ActivityManager;
import android.app.usage.StorageStats;
import android.app.usage.StorageStatsManager;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.os.UserHandle;
import android.os.storage.StorageManager;

import androidx.annotation.RequiresApi;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.UUID;

public class AppsUtils {
    public static boolean isAppRunning(ActivityManager activityManager, String packageName) {
        List<ActivityManager.RunningAppProcessInfo> runningAppProcesses = activityManager.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningAppProcesses) {
            if (processInfo.processName.equals(packageName)) {
                return true; // 应用正在运行
            }
        }
        return false; // 应用未运行
    }

    public static void killApplication(ActivityManager activityManager, String packageName){
        activityManager.killBackgroundProcesses(packageName);
    }

    public static void forceStopPackage(ActivityManager activityManager,String packageName){
        try {
            Method method = Class.forName("android.app.ActivityManager").getMethod("forceStopPackage", String.class);
            method.invoke(activityManager, packageName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public static long[] getCacheSize(PackageManager packageManager, Context context, String packageName, Handler handler) {
        StorageStatsManager storageStatsManager = (StorageStatsManager) context.getSystemService(Context.STORAGE_STATS_SERVICE);
        try {
            UUID uuid = StorageManager.UUID_DEFAULT;
            StorageStats storageStats = storageStatsManager.queryStatsForPackage(uuid, packageName, UserHandle.getUserHandleForUid(packageManager.getPackageUid(packageName, 0)));
            Message message = new Message();
            message.what = 0;
            message.obj = new long[]{storageStats.getDataBytes(),storageStats.getCacheBytes(),storageStats.getAppBytes()};
            handler.sendMessage(message);
        } catch (PackageManager.NameNotFoundException | IOException e) {
            e.printStackTrace();
        }
        return new long[2];
    }
}
